package com.herionthenet;

import java.nio.ByteBuffer;
import java.util.LinkedList;
import java.util.List;

public class SimpleFrameDecoder extends FrameDecoder {

	public final static byte[] DELIMITER = new byte[]{0x0D, 0x0A, (byte)0xFF, 0};
	public SimpleFrameDecoder() {		
		super(DELIMITER, FramerDataOption.TEXT);
	}	
	
	public List<byte[]> decode(ByteBuffer buffer){
		List<byte[]> frames = new LinkedList<byte[]>();
		byte[] array = buffer.array();
		
		int startPosition = 0;		
						
		for(int i = 0; i < buffer.limit(); i++){			
			if(endOfFrame(array, i)){				
				int frameLength = (i + 1) - startPosition - delimiters.length;
				
				byte[] byteFramed = new byte[frameLength];				
				System.arraycopy(array, startPosition, byteFramed, 0, frameLength);							
				frames.add(byteFramed);								
				
				startPosition = i + 1;
			}			
			
		}
		
		buffer.position(startPosition);		
		return frames;
	}
}
